<template>
    <div class="dialog-background" @click="onModalClicked" :data-id="'dialog-' + uuid" v-if="visible">
        <div class="dialog-root with-shadow" @click.stop="noop">
            <div class="flexable v-center p-10 dialog-header" v-if="showHeader">
                <slot name="header" v-if="showHeader">
                    <div class="auto-grow">{{ title }}</div>
                </slot>
                <a class="dialog-close-button" @click="fadeout">
                    <i class="fa fa-xmark" />
                </a>
            </div>
            <div class="dialog-body">
                <slot />
            </div>
            <div class="p-10 dialog-foot" v-if="showFooter">
                <slot name="footer">
                    <a class="clickable plain" @click="fadeout">关闭</a>
                </slot>
            </div>
        </div>
    </div>
</template>

<script>
import $ from 'jquery';
import { noop, closeDialog } from "@/utils/functions";
import {dialogStack, Bus} from "@/utils/metadata";
import logo from "@/assets/images/cai-logo-128.png";

const holder = { root: undefined, };
export default {
    props: {
        modelValue: Boolean,
        showHeader: { type: Boolean, default: true },
        showFooter: { type: Boolean, default: true },
        title: String,
        hideOnClickModal: {type: Boolean, default: true}
    },
    emits: ['update:modelValue', 'closed'],
    computed: {
        visible: {
            get () { return this.modelValue; },
            set (value) { this.$emit ('update:modelValue', value) },
        }
    },
    data () {
        return {
            logo,
            uuid: Math.random ().toString (16).substring (2),
        }
    },
    methods: {
        noop,
        fadeout () {
            let vue = this;
            holder.root.fadeOut (() => {
                vue.$emit ('update:modelValue', false);
                dialogStack.pop ();
                if (!dialogStack.length) {
                    $(document).unbind ('keyup', closeDialog);
                }
            });
        },
        onModalClicked () {
            if (this.hideOnClickModal) {
                this.fadeout ();
            }
        },
    },
    mounted () {
        if (!dialogStack.length) {
            $(document).on ('keyup', closeDialog);
        }
        dialogStack.push (this.uuid);
        this.$nextTick (() => {
            holder.root = $('.dialog-background[data-id=dialog-' + this.uuid + ']');
            holder.root.fadeIn ();
        });
        Bus.on ('close-dialog', uuid => {
            if (uuid === this.uuid) {
                this.fadeout ();
            }
        })
    },
};
</script>

<style scoped>

</style>